import 'package:flutter/material.dart';
import '../constants/colors.dart';
import '../widgets/gradient_background.dart';
import '../widgets/app_button.dart';
import '../widgets/app_card.dart';
import '../models/hexagram.dart';
import '../services/hexagram_service.dart';
import 'hexagram_detail_page.dart';
import 'share_poster_page.dart';

class DivinationResultPage extends StatefulWidget {
  final Map<String, dynamic>? arguments;
  
  const DivinationResultPage({
    Key? key,
    this.arguments,
  }) : super(key: key);

  @override
  State<DivinationResultPage> createState() => _DivinationResultPageState();
}

class _DivinationResultPageState extends State<DivinationResultPage> {
  late Hexagram _hexagram;
  final HexagramService _hexagramService = HexagramService();
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _generateHexagram();
  }

  Future<void> _generateHexagram() async {
    final divinationType = widget.arguments?['type'] ?? 'time';
    
    try {
      if (divinationType == 'voice') {
        final text = widget.arguments?['text'] ?? '默认问题';
        _hexagram = await _hexagramService.generateFromText(text);
      } else if (divinationType == 'photo') {
        final imagePath = widget.arguments?['imagePath'] ?? '';
        _hexagram = await _hexagramService.generateFromImage(imagePath);
      } else if (divinationType == 'number') {
        final number1 = widget.arguments?['number1'] ?? 1;
        final number2 = widget.arguments?['number2'] ?? 1;
        _hexagram = _hexagramService.generateFromNumbers(number1, number2);
      } else {
        // 默认使用时间起卦
        _hexagram = _hexagramService.generateFromTime(DateTime.now());
      }
    } catch (e) {
      // 如果生成失败，使用默认卦象
      _hexagram = _hexagramService.generateFromTime(DateTime.now());
    }
    
    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        body: GradientBackground(
          child: const Center(
            child: CircularProgressIndicator(
              color: Colors.white,
            ),
          ),
        ),
      );
    }
    
    final question = widget.arguments?['question'] ?? '今日运势';
    
    return Scaffold(
      body: GradientBackground(
        child: SafeArea(
          child: Column(
            children: [
              // 顶部栏
              Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 15,
                ),
                child: Row(
                  children: [
                    IconButton(
                      icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
                      onPressed: () => Navigator.pop(context),
                    ),
                    Expanded(
                      child: Center(
                        child: Text(
                          '卦象解读',
                          style: const TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                        ),
                      ),
                    ),
                    IconButton(
                      icon: const Icon(Icons.share, color: Colors.black),
                      onPressed: () {
                        print("顶部按钮跳转到分享海报页: ${_hexagram.name}");
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (context) => SharePosterPage(
                              hexagram: _hexagram,
                            ),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
              
              // 主体内容
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    children: [
                      const SizedBox(height: 8),
                      Text(
                        '今日卦象：${_hexagram.name}',
                        style: const TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                          color: Colors.black,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '问题：$question',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.black.withOpacity(0.7),
                        ),
                      ),
                      const SizedBox(height: 24),
                      
                      // 卦象图和五行关系
                      AppCard(
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    _hexagram.upperSymbol,
                                    style: const TextStyle(
                                      fontSize: 72,
                                      color: AppColors.primaryGradientStart,
                                    ),
                                  ),
                                  const SizedBox(width: 16),
                                  Text(
                                    _hexagram.lowerSymbol,
                                    style: const TextStyle(
                                      fontSize: 72,
                                      color: AppColors.primaryGradientStart,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              Text(
                                '五行：${_hexagram.upperElement}${_hexagram.lowerElement}',
                                style: const TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                  color: AppColors.textPrimary,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      
                      // 卦象直解
                      AppCard(
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '卦象直解',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: AppColors.primaryGradientStart,
                                ),
                              ),
                              const SizedBox(height: 12),
                              Text(
                                _hexagram.description,
                                style: const TextStyle(
                                  fontSize: 16,
                                  height: 1.5,
                                  color: AppColors.textPrimary,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      
                      // AI解读
                      AppCard(
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                'AI解读 (结合问题场景)',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: AppColors.primaryGradientStart,
                                ),
                              ),
                              const SizedBox(height: 12),
                              Text(
                                _getAIInterpretation(question),
                                style: const TextStyle(
                                  fontSize: 16,
                                  height: 1.5,
                                  color: AppColors.textPrimary,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      
                      // 行动建议
                      AppCard(
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '行动建议',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: AppColors.primaryGradientStart,
                                ),
                              ),
                              const SizedBox(height: 12),
                              ..._getActionSuggestions().map((suggestion) => 
                                _buildActionItem(suggestion)
                              ).toList(),
                            ],
                          ),
                        ),
                      ),
                      
                      // 查看详情按钮
                      const SizedBox(height: 24),
                      AppPrimaryButton(
                        text: '查看卦象详解',
                        onPressed: () {
                          print("跳转到卦象详情页: ${_hexagram.name}");
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) => HexagramDetailPage(
                                hexagram: _hexagram,
                              ),
                            ),
                          );
                        },
                      ),
                      
                      // 分享按钮
                      const SizedBox(height: 16),
                      AppPrimaryButton(
                        text: '生成分享海报',
                        onPressed: () {
                          print("跳转到分享海报页: ${_hexagram.name}");
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) => SharePosterPage(
                                hexagram: _hexagram,
                              ),
                            ),
                          );
                        },
                      ),
                      
                      // 准确性反馈
                      const SizedBox(height: 24),
                      Text(
                        '对本次解卦结果满意吗？',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.black.withOpacity(0.7),
                        ),
                      ),
                      const SizedBox(height: 8),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          _buildFeedbackButton('很准！👍', true),
                          const SizedBox(width: 16),
                          _buildFeedbackButton('不准 👎', false),
                        ],
                      ),
                      
                      // 免责声明
                      const SizedBox(height: 24),
                      Text(
                        '* 本解读基于古籍参考与AI技术生成，仅供参考，不作为迷信依据。',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.black.withOpacity(0.5),
                        ),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 40),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  Widget _buildActionItem(String text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(
            Icons.check_circle,
            size: 16,
            color: AppColors.primaryGradientStart,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              text,
              style: const TextStyle(
                fontSize: 16,
                height: 1.5,
                color: AppColors.textPrimary,
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildFeedbackButton(String text, bool isPositive) {
    return ElevatedButton(
      onPressed: () {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(isPositive ? '感谢您的反馈！' : '感谢您的反馈，我们会继续改进！'),
            duration: const Duration(seconds: 2),
          ),
        );
      },
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.white.withOpacity(0.2),
        foregroundColor: Colors.black,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      ),
      child: Text(text),
    );
  }
  
  String _getAIInterpretation(String question) {
    // 这里可以根据问题和卦象生成不同的解读
    // 实际应用中可以调用NLP API或本地模型
    if (question.contains('财运') || question.contains('金钱')) {
      return '${_hexagram.name}卦在财运方面预示着${_getFinancialInterpretation()}';
    } else if (question.contains('健康') || question.contains('身体')) {
      return '${_hexagram.name}卦在健康方面提醒您${_getHealthInterpretation()}';
    } else if (question.contains('感情') || question.contains('爱情')) {
      return '${_hexagram.name}卦在感情方面显示${_getLoveInterpretation()}';
    } else {
      return '${_hexagram.name}卦预示着您当前的整体运势处于${_getGeneralInterpretation()}';
    }
  }
  
  String _getFinancialInterpretation() {
    // 简化版的财运解读
    final interpretations = [
      '近期财运稳健，适合稳妥投资，避免冒险。',
      '财源广进，但需注意量入为出，避免不必要的开支。',
      '财运波动，建议谨慎理财，避免大额支出。',
      '有意外收获的可能，但也要防范突发支出。',
      '财运上升，适合把握机会，但不宜过于激进。',
    ];
    
    return interpretations[_hexagram.name.hashCode % interpretations.length];
  }
  
  String _getHealthInterpretation() {
    // 简化版的健康解读
    final interpretations = [
      '身体状况良好，但仍需注意作息规律，保持充足睡眠。',
      '可能有些疲劳，建议适当休息，避免过度劳累。',
      '整体健康稳定，建议保持适量运动，增强体质。',
      '需要关注饮食健康，避免过于油腻或刺激性食物。',
      '精神状态不错，但要注意调节压力，保持心情愉快。',
    ];
    
    return interpretations[_hexagram.name.hashCode % interpretations.length];
  }
  
  String _getLoveInterpretation() {
    // 简化版的感情解读
    final interpretations = [
      '感情稳定发展，沟通是维系关系的关键。',
      '可能遇到一些小波折，但只要坦诚相待，问题终将解决。',
      '桃花运旺盛，单身者有望遇到心仪对象。',
      '感情需要更多的耐心和包容，避免冲动决策。',
      '关系进入新阶段，相互理解和支持尤为重要。',
    ];
    
    return interpretations[_hexagram.name.hashCode % interpretations.length];
  }
  
  String _getGeneralInterpretation() {
    // 简化版的总体运势解读
    final interpretations = [
      '上升阶段，各方面都有不错的发展，可以适当把握机会。',
      '平稳期，适合稳扎稳打，循序渐进地推进计划。',
      '小有波动，需要保持冷静和耐心，避免冲动决策。',
      '转折点，可能面临一些变化和挑战，但也蕴含新的机遇。',
      '调整期，适合反思和规划，为未来发展打好基础。',
    ];
    
    return interpretations[_hexagram.name.hashCode % interpretations.length];
  }
  
  List<String> _getActionSuggestions() {
    // 根据卦象生成行动建议
    final List<String> baseSuggestions = [
      '保持积极心态，相信自己的判断和能力。',
      '适当寻求他人建议，集思广益往往能带来更好的结果。',
      '关注身心健康，保持规律作息和适量运动。',
    ];
    
    // 根据卦象特性添加特定建议
    if (_hexagram.name.contains('乾') || _hexagram.name.contains('天')) {
      baseSuggestions.add('发挥领导才能，主动把握机会，展现自信和决断力。');
    } else if (_hexagram.name.contains('坤') || _hexagram.name.contains('地')) {
      baseSuggestions.add('保持谦逊和包容，厚积薄发，等待合适时机。');
    } else if (_hexagram.name.contains('震') || _hexagram.name.contains('雷')) {
      baseSuggestions.add('准备迎接变化和挑战，保持警觉和适应能力。');
    } else if (_hexagram.name.contains('坎') || _hexagram.name.contains('水')) {
      baseSuggestions.add('面对困难保持冷静，寻找突破口，化险为夷。');
    } else if (_hexagram.name.contains('艮') || _hexagram.name.contains('山')) {
      baseSuggestions.add('适当停下脚步，反思和调整，不要盲目前进。');
    } else if (_hexagram.name.contains('巽') || _hexagram.name.contains('风')) {
      baseSuggestions.add('保持灵活性和适应性，随机应变，顺势而为。');
    } else if (_hexagram.name.contains('离') || _hexagram.name.contains('火')) {
      baseSuggestions.add('展现才华和智慧，但注意不要过于张扬，保持内敛。');
    } else if (_hexagram.name.contains('兑') || _hexagram.name.contains('泽')) {
      baseSuggestions.add('加强沟通和交流，表达自己的想法，建立良好人际关系。');
    }
    
    return baseSuggestions;
  }
}